import { Module } from 'vuex'
import LocallCache from '@/utils/cache'
import type { IloginState } from './type'
import type { TRootState } from '../type'
import { accountLoginRequest, requestUserInfoById } from '@/service/login/login'
import { IAccount } from '@/service/login/type'
import router from '@/router'
const loginModule: Module<IloginState, TRootState> = {
  namespaced: true,
  state() {
    return {
      token: LocallCache.getCache('token') || '',
      userInfo: LocallCache.getCache('userInfo') || {}
    }
  },
  getters: {},
  mutations: {
    setToken(state, token: string) {
      state.token = token
      LocallCache.setCache('token', token)
    },
    setUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
      LocallCache.setCache('userInfo', userInfo)
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)
      console.log(loginResult)
      const token = loginResult.data
      commit('setToken', token)
      const userInfoResult = await requestUserInfoById()
      const userInfo = userInfoResult.data
      console.log(userInfo)
      commit('setUserInfo', userInfo)
      //跳到首页
      router.push('/')
    },
    setupStore({ commit }) {
      const token = LocallCache.getCache('token')
      if (token) {
        commit('setToken', token)
      }
      const userInfo = LocallCache.getCache('userInfo')
      if (userInfo) {
        commit('setUserInfo', userInfo)
      }
    }
  }
}
export default loginModule
